package com.spring.quartz.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <h3>partitionjob</h3>
 * <p>读取配置文件工具类</p>
 *
 * @author : hduong
 * @version : 1.0
 * @date : 2019-12-17 18:21
 **/
public class PropertiesUtils {

    private static final Logger LOG = LoggerFactory.getLogger(PropertiesUtils.class);

    protected static Properties DEFAULT_PROP = null;

    private static final String CONFIG_PROPERTIES = "config.properties";

    protected static Map<String, Properties> ALL_PROP = new ConcurrentHashMap<>();

    static {
        if (DEFAULT_PROP == null) {
            DEFAULT_PROP = loadProperties(CONFIG_PROPERTIES);
        }
    }

    /**
     * 功能描述: 
     * <获取config 配置文件的 属性>
     * @param name
     * @date : 2019/12/19 9:26
     * @return : java.lang.String
     * @author : hduong
     */
    public static String getProperty(String name) {
        return getProperties(CONFIG_PROPERTIES).getProperty(name);
    }

    /**
     * 功能描述: 
     * <获取 配置文件的属性>
     * @param fileName
     * @param name
     * @date : 2019/12/19 9:25
     * @return : java.lang.String
     * @author : hduong
     */
    public static String getProperty(String fileName, String name) {
        return getProperties(fileName).getProperty(name);
    }

    /**
     * 功能描述: 
     * <获取 对应的资源文件>
     * @param fileName
     * @date : 2019/12/19 9:19
     * @return : java.util.Properties
     * @author : hduong
     */
    public static Properties getProperties(String fileName) {
        if(StringUtils.isEmpty(fileName)) {
            return DEFAULT_PROP;
        }
        Properties properties = ALL_PROP.get(fileName);
        if(properties == null) {
            properties = loadProperties(fileName);
            ALL_PROP.put(fileName, properties);
        }
        return properties;
    }


    /**
     * 功能描述: 
     * <加载 资源文件>
     * @param fileName
     * @date : 2019/12/19 9:14
     * @return : java.util.Properties
     * @author : hduong
     */
    private static Properties loadProperties(String fileName) {
        Properties retProp = new Properties();
        InputStream inputStream = PropertiesUtils.class.getClassLoader().getResourceAsStream(fileName);
        if(inputStream == null) {
            throw new RuntimeException("找不到资源!");
        } else {
            try {
                retProp.load(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
                LOG.error("加载资源失败: {}", e);
            }
        }
        return retProp;

    }


}
